package com.swing.sky.web.generator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.swing.sky.web.generator.constant.ModuleConstants;
import com.swing.sky.web.generator.domain.Module;
import com.swing.sky.web.generator.domain.ModuleHouse;
import com.swing.sky.web.generator.util.ModuleHouseInitializer;
import com.swing.sky.web.generator.util.OsUtil;
import com.swing.sky.web.generator.util.VelocityContextBuilder;
import com.swing.sky.web.generator.util.VelocityInitializer;

/**
 * @author swing
 */
public class Gen {

    public static void main(String[] args) throws IOException {
        // 清空文件夹
        // File oldFile = new File(Configs.readSky("outputPath"));
        // if (oldFile.exists())
        // deleteFolder(oldFile);
        List<ModuleHouse> moduleHouses = ModuleHouseInitializer.buildModuleHouses();
        Gen genService = new Gen();
        for (ModuleHouse moduleHouse : moduleHouses) {
            for (Module module : moduleHouse.getModules()) {
                genService.generatorCode(moduleHouses, moduleHouse, module);
            }
        }
        System.out.println("GEN OVER");
    }

    public void generatorCode(List<ModuleHouse> moduleHouses, ModuleHouse moduleHouse, Module module) {
        // 初始化模板引擎
        VelocityInitializer.initVelocity();

        Template template = Velocity.getTemplate(module.getTemplatePath(), "UTF-8");

        // 获取输出的文件文件夹路径
        File file = new File(module.getAbsolutePath());
        if (!file.exists()) {
            file.mkdirs();
        }
        // 获取文件名
        String fileName = module.getFileName() + module.getExtension();
        // 获取文件名并输出
        File file1 = new File(module.getAbsolutePath() + OsUtil.getSeparator() + fileName);
        String customContent = "";
        if (!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (module.getModuleName().equals(ModuleConstants.SERVICE))
                // service如果存在，不修改
                return;
            // 源文件已有内容，保留自定义内容
            StringBuilder builder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file1), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line).append(System.lineSeparator());
                }
                String inputText = builder.toString();
                Pattern pattern = null;
                if (module.getExtension().equals(".xml")) {
                    pattern = Pattern.compile(
                            "(?<=<!-- Custom info -->\\r?\\n)(.*?)(?=\\r?\\n\\s*<!-- Custom info -->)",
                            Pattern.DOTALL);
                } else {
                    pattern = Pattern.compile("(?<=// Custom info\\r?\\n)(.*?)(?=\\r?\\n\\s*// Custom info)",
                            Pattern.DOTALL);
                }
                Matcher matcher = pattern.matcher(inputText);
                if (matcher.find()) {
                    customContent = matcher.group(1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 获取渲染模板需要的上下文
        VelocityContext velocityContext = VelocityContextBuilder.buildVelocityContext(moduleHouses, moduleHouse,
                module);
        // 出入渲染的文件
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file1), "UTF-8"));
            String s = stringWriter.toString();
            if (!customContent.isEmpty()) {
                String regex2 = "";
                if (module.getExtension().equals(".xml")) {
                    regex2 = "(?<=<!-- Custom info -->\\\r?\\n)([\\s\\S]*?)(?=\\\r?\\n[ \\t]*<!-- Custom info -->)";
                } else {
                    regex2 = "(?<=\\/\\/ Custom info\\\r?\\n)([\\s\\S]*?)(?=\\\r?\\n[ \\t]*\\/\\/ Custom info)";
                }
                s = s.replaceFirst(regex2, customContent);
            }
            writer.write(s);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void deleteFolder(File folder) {
        // 遍历文件夹中的所有文件和子文件夹
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                // 如果是文件，直接删除
                if (file.isFile()) {
                    file.delete();
                } else if (file.isDirectory()) {
                    // 如果是子文件夹，递归删除
                    deleteFolder(file);
                }
            }
        }
        // 删除文件夹本身
        folder.delete();
    }

}
